package com.spark.modules.generation.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spark.common.core.Result;
import com.spark.common.core.entity.generation.GenModel;
import com.spark.common.core.entity.generation.GenModelFields;
import com.spark.modules.generation.entity.GenDefaultFields;
import com.spark.modules.generation.entity.GenFieldMapping;
import com.spark.modules.generation.entity.vo.GenModelFieldsVo;
import com.spark.modules.generation.entity.vo.GenModelVo;
import com.spark.modules.generation.mapper.GenDefaultFieldsMapper;
import com.spark.modules.generation.mapper.GenFieldMappingMapper;
import com.spark.modules.generation.mapper.GenModelFieldsMapper;
import com.spark.modules.generation.mapper.GenModelMapper;
import com.spark.modules.generation.service.IGenModelFieldsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 模型字段Service
 *
 * @author LYCHEE
 * @date 2025/02/24 15:25
 */
@Service
public class GenModelFieldsServiceImpl extends ServiceImpl<GenModelFieldsMapper, GenModelFields> implements IGenModelFieldsService {

    @Resource
    private GenModelMapper genModelMapper;
    @Resource
    private GenDefaultFieldsMapper genDefaultFieldsMapper;
    @Resource
    private GenFieldMappingMapper genFieldMappingMapper;


    /**
     * 通过模型ID查询字段
     *
     * @param modelCode 模型CODE
     * @return 字段信息
     */
    @Override
    public Result<?> queryModelFields(String modelCode) {
        LambdaQueryWrapper<GenModel> modelLambdaQueryWrapper = new LambdaQueryWrapper<>();
        modelLambdaQueryWrapper.eq(GenModel::getModelCode, modelCode);
        GenModel genModel = genModelMapper.selectOne(modelLambdaQueryWrapper);
        if (Objects.isNull(genModel)){
            return Result.fail("模型信息异常");
        }
        // 从数据库中查询是否存在字段信息
        LambdaQueryWrapper<GenModelFields> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(GenModelFields::getModelId, genModel.getId()).orderByAsc(GenModelFields::getCreateTime);
        List<GenModelFields> genModelFields = baseMapper.selectList(lambdaQueryWrapper);
        // 根据表结构查询默认的字段
        LambdaQueryWrapper<GenDefaultFields> defaultFieldsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        defaultFieldsLambdaQueryWrapper.eq(GenDefaultFields::getIsCommon, 0);
        if ("tree".equals(genModel.getModelCharacter())){
            defaultFieldsLambdaQueryWrapper.or().eq(GenDefaultFields::getIsCommon, 1).eq(GenDefaultFields::getTableType, "tree");
        }
        defaultFieldsLambdaQueryWrapper.orderByAsc(GenDefaultFields::getCreateTime);
        List<GenDefaultFields> defaultFields = genDefaultFieldsMapper.selectList(defaultFieldsLambdaQueryWrapper);

        if (CollectionUtils.isEmpty(genModelFields)){
            for (GenDefaultFields defaultField : defaultFields) {
                GenModelFields fieldsModel = new GenModelFields();
                fieldsModel.setModelId(null);
                fieldsModel.setFieldName(defaultField.getFieldName());
                fieldsModel.setFieldAnnotation(defaultField.getFieldAnnotation());
                fieldsModel.setFieldRemark(null);
                fieldsModel.setFieldType(defaultField.getFieldType());
                fieldsModel.setFieldLength(defaultField.getFieldLength());
                fieldsModel.setFieldDecimalPoint(defaultField.getDecimalPoint());
                fieldsModel.setFieldDefaultVal(null);
                if ("del_flag".equals(defaultField.getFieldName())){
                    fieldsModel.setFieldDefaultVal("0");
                }
                fieldsModel.setFieldPrimaryKey(defaultField.getIsPrimaryKey() == 0);
                fieldsModel.setFieldNotNull(!(defaultField.getIsNull() == 0));
                fieldsModel.setFieldUnique(false);
                fieldsModel.setIsHandle(Boolean.FALSE);
                fieldsModel.setFieldSelect(0);
                fieldsModel.setFieldRelevance(0);
                fieldsModel.setFieldSort(0);
                fieldsModel.setFieldRule(0);
                fieldsModel.setComponentName("Input");
                if ("pid".equals(defaultField.getFieldName())){
                    fieldsModel.setFieldDefaultVal("0");
                    fieldsModel.setComponentName("ApiTreeSelect");
                }
                if ("is_leaf".equals(defaultField.getFieldName())) {
                    fieldsModel.setFieldDefaultVal("0");
                }
                genModelFields.add(fieldsModel);
            }
        } else {
            List<GenModelFieldsVo> res = new ArrayList<>();
            List<String> fields = defaultFields.stream().map(GenDefaultFields::getFieldName).collect(Collectors.toList());
            LambdaQueryWrapper<GenFieldMapping> fieldMappingLambdaQueryWrapper = new LambdaQueryWrapper<>();
            fieldMappingLambdaQueryWrapper.eq(GenFieldMapping::getStatus, 0);
            List<GenFieldMapping> fieldMappings = genFieldMappingMapper.selectList(fieldMappingLambdaQueryWrapper);
            for (GenModelFields genModelField : genModelFields) {
                GenModelFieldsVo fieldsVo = new GenModelFieldsVo(genModelField);
                if (fields.contains(fieldsVo.getFieldName())){
                    fieldsVo.setIsHandle(Boolean.FALSE);
                }
                for (GenFieldMapping fieldMapping : fieldMappings) {
                    if (fieldMapping.getFieldType().equals(fieldsVo.getFieldType())){
                        fieldsVo.setFieldPackagePath(fieldMapping.getJavaFieldPackage());
                        break;
                    }
                }
                res.add(fieldsVo);
            }
            return Result.ok(res);
        }
        return Result.ok(genModelFields);
    }

    /**
     * 新增或编辑字段信息
     *
     * @param modelVo 模型信息
     * @return 是否成功
     */
    @Transactional(rollbackFor = {Exception.class})
    @Override
    public Result<?> saveOrEdit(GenModelVo modelVo) {
        if (StringUtils.isEmpty(modelVo.getModelCode())){
            return Result.fail("模型编码异常");
        }
        LambdaQueryWrapper<GenModel> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(GenModel::getModelCode, modelVo.getModelCode());
        GenModel genModel = genModelMapper.selectOne(lambdaQueryWrapper);
        if (Objects.isNull(genModel)){
            return Result.fail("模型编码：" + modelVo.getModelCode() + " 没有对应的模型");
        }
        List<GenModelFields> modelFields = modelVo.getModelFields();
        if (CollectionUtils.isEmpty(modelFields)){
            return Result.fail("模型字段错误");
        }
        // 真实删除字段信息
        baseMapper.deleteBatchByModelId(genModel.getId());
        modelFields.forEach(item -> {
            item.setModelId(genModel.getId());
            baseMapper.insert(item);
        });
        if (!Objects.isNull(modelVo.getModelSyncStatus())){
            genModel.setModelSyncStatus(modelVo.getModelSyncStatus());
            genModelMapper.updateById(genModel);
        }
        return Result.ok("保存成功");
    }
}
